package com.mlatent.mvvmproject.app.base

import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.kingja.loadsir.core.LoadService
import com.lihao.jetpackcore.base.BaseViewModel
import com.lihao.jetpackcore.base.BaseVmActivity
import com.lihao.jetpackcore.ext.getAppViewModel
import com.lihao.jetpackcore.ext.nav
import com.mlatent.mvvmproject.R
import com.mlatent.mvvmproject.app.event.CacheViewModel
import com.mlatent.mvvmproject.app.event.EventViewModel

abstract class BaseActivity<VM : BaseViewModel> : BaseVmActivity<VM>() {

    private var dialog: MaterialDialog? = null

    lateinit var loadSir: LoadService<Any>

    var toolbar: Toolbar? = null

    var tvTitle: TextView? = null

    /**
     * Application全局的ViewModel，里面存放了一些账户信息，基本配置信息等
     */
    val cacheViewModel: CacheViewModel by lazy { getAppViewModel<CacheViewModel>() }

    /**
     * Application全局的ViewModel，用于发送全局通知操作
     */
    val eventViewModel: EventViewModel by lazy { getAppViewModel<EventViewModel>() }

    /**
     * 创建liveData观察者
     */
    override fun createObserver() {}

    /**
     * 标题栏
     */
    fun initTitle(
        titleStr: String = "",
        isShowBack: Boolean = true,
        backImg: Int = R.drawable.ic_back_24,
        onBack: (() -> Unit)? = null
    ) {
        toolbar = findViewById(R.id.toolbar)
        tvTitle = findViewById(R.id.tvTitle)
        tvTitle?.text = titleStr
        toolbar?.let {
            it.title = ""
            if (isShowBack) {
                it.setNavigationIcon(backImg)
            }
            it.setNavigationOnClickListener {
                if (onBack == null) {
                    finish()
                } else {
                    onBack.invoke()
                }
            }
        }
    }

    /**
     * 打开等待框
     */
    override fun showLoading(message: String) {
        if (dialog == null) {
            dialog = this.let {
                MaterialDialog(it)
                    .cancelable(true)
                    .cancelOnTouchOutside(false)
                    .customView(R.layout.layout_custom_progress_dialog_view)
                    .lifecycleOwner(this)
            }
            dialog?.getCustomView()?.run {
                this.findViewById<TextView>(R.id.loading_tips).text = message
//                this.findViewById<ProgressBar>(R.id.progressBar).indeterminateTintList =
//                    SettingUtil.getOneColorStateList(R.color.colorPrimary)
            }
        }
        dialog?.show()
    }

    /**
     * 关闭等待框
     */
    override fun dismissLoading() {
        dialog?.dismiss()
    }

}